package per.hx.bs.util;


import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import per.hx.bs.base.domain.ExcelData;

import java.awt.Color;
import java.net.URLEncoder;

/**
 * excel工具包
 *
 * @author HuXing
 * @date 2018/4/27  11:24
 */
public class ExcelUtils {

    public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        exportExcel(data, response.getOutputStream());
    }

    public static void exportExcel(ExcelData data, OutputStream out) throws Exception {

        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //此处需要关闭 wb 变量
            out.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {

        int rowIndex;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles(), data.getSubject(), data.getMessage());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
        autoSizeColumns(sheet, data.getTitles().size() + 1);

    }

    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles, String subject, String message) {
        int rowIndex = 2;
        int colIndex;

        //1.1创建合并单元格对象
        //起始行,结束行,起始列,结束列
        CellRangeAddress callSubject = new CellRangeAddress(0, 0, 0, 7);
        CellRangeAddress callMessage = new CellRangeAddress(1, 1, 0, 7);


        Font subjectFont = wb.createFont();
        subjectFont.setFontName("黑体");
        subjectFont.setBoldweight(Short.MAX_VALUE);
        subjectFont.setFontHeightInPoints((short) 20);
        subjectFont.setColor(IndexedColors.BLACK.index);

        Font messageFont = wb.createFont();
        messageFont.setFontName("黑体");
        messageFont.setBoldweight(Short.MAX_VALUE);
        messageFont.setFontHeightInPoints((short) 10);
        messageFont.setColor(IndexedColors.BLACK.index);

        Font titleFont = wb.createFont();
        titleFont.setFontName("黑体");
        titleFont.setBoldweight(Short.MAX_VALUE);
        titleFont.setFontHeightInPoints((short) 14);
        titleFont.setColor(IndexedColors.LIGHT_GREEN.index);

        XSSFCellStyle subjectStyle = wb.createCellStyle();
        subjectStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        subjectStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        subjectStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        subjectStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        subjectStyle.setFont(subjectFont);
        //setBorder(subjectStyle, new XSSFColor(new Color(0, 0, 0)));

        XSSFCellStyle messageStyle = wb.createCellStyle();
        messageStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        messageStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        messageStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        messageStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        messageStyle.setFont(messageFont);
        // setBorder(messageStyle, new XSSFColor(new Color(0, 0, 0)));


        XSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(0, 0, 0)));
        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, new XSSFColor(new Color(182, 184, 192)));


        sheet.addMergedRegion(callSubject);
        sheet.addMergedRegion(callMessage);


        // 使用RegionUtil类为合并后的单元格添加边框
        RegionUtil.setBorderBottom(1, callSubject, sheet, wb);
        RegionUtil.setBorderLeft(1, callSubject, sheet, wb);
        RegionUtil.setBorderRight(1, callSubject, sheet, wb);
        RegionUtil.setBorderTop(1, callSubject, sheet, wb);

        colIndex = 0;
        //标题
        Row subjectRow = sheet.createRow(0);
        Cell subjectRowCell = subjectRow.createCell(0);
        subjectRow.setHeightInPoints(40);
        subjectRowCell.setCellValue(subject);
        subjectRowCell.setCellStyle(subjectStyle);

        //导出信息
        Row messageRow = sheet.createRow(1);
        messageRow.setHeightInPoints(20);
        Cell messageRowCell = messageRow.createCell(0);
        messageRowCell.setCellValue(message);
        messageRowCell.setCellStyle(messageStyle);

        //title
        Row titleRow = sheet.createRow(rowIndex);
        titleRow.setHeightInPoints(23);

        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }

        rowIndex++;
        return rowIndex;
    }

    private static void writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
        int colIndex;

        Font dataFont = wb.createFont();
        dataFont.setFontName("宋体");
        dataFont.setFontHeightInPoints((short) 10);
        dataFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        dataStyle.setFont(dataFont);
        setBorder(dataStyle, new XSSFColor(new Color(0, 0, 0)));

        for (List<Object> rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);
            dataRow.setHeightInPoints(25);
            colIndex = 0;

            for (Object cellData : rowData) {
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                    cell.setCellValue(cellData.toString());
                } else {
                    cell.setCellValue("");
                }
                cell.setCellStyle(dataStyle);
                colIndex++;
            }
            rowIndex++;
        }
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = sheet.getColumnWidth(i) + 100;
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }
    }

    private static void setBorder(XSSFCellStyle style, XSSFColor color) {
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderColor(BorderSide.TOP, color);
        style.setBorderColor(BorderSide.LEFT, color);
        style.setBorderColor(BorderSide.RIGHT, color);
        style.setBorderColor(BorderSide.BOTTOM, color);
    }
}